package com.jams.goodox.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MusicService extends Service {
    public MediaPlayer mediaPlayer;
    public boolean tag = false;
    public static String url;

    public MusicService() {
        Log.d("TTTT","-------222-------" + url);
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
            mediaPlayer.setLooping(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //  通过 Binder 来保持 Activity 和 Service 的通信
    public MyBinder binder = new MyBinder();
    public class MyBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

    public void playOrPause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        } else {
            mediaPlayer.start();
        }
    }

    public void seekBack(){
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()){
                int current = mediaPlayer.getCurrentPosition();
                if(current < 5000){
                    mediaPlayer.seekTo(0);
                }else {
                    mediaPlayer.seekTo(current - 5000);
                }
            }
        }
    }


    public void seekForword(){
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()){
                int current = mediaPlayer.getCurrentPosition();
                if(current + 5000 > mediaPlayer.getDuration()){
                    mediaPlayer.seekTo(mediaPlayer.getDuration());
                }else {
                    mediaPlayer.seekTo(current + 5000);
                }
            }
        }
    }


    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(url);
                mediaPlayer.prepare();
                mediaPlayer.seekTo(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void release(){
        if(mediaPlayer != null){
            mediaPlayer.release();

        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
}

